module Mongowiki
  class Wikiparser
    def self.parse(filename)
      pages = []
      File.open(filename) do |file|
        while(true)
          page = parse_one(file)
          break if page.nil?

          pages << page
        end
      end
      pages
    end
    
    private
    
    def self.parse_one(file)
      page = Wikipage.new
      
      line = file.gets
      return nil if !line
      
      page.title    = line[/Title: (.+)/, 1]
      page.url      = file.gets[/URL: (.+)/, 1]
      
      if line = file.gets[/Keywords: (.+)/, 1]
        page.keywords = line.strip.split(',')
      end
      
      if file.gets =~ /Links:/
        while line = file.gets
          break if line == "\n"
          page.links.push(line.strip)
        end
      end
      
      if file.gets =~ /Citations:/
        while line = file.gets
          break if line == "\n" || line == ''
          page.citations.push(line.strip)
        end
      end
      
      page
    end
  end
end